package com.company.utils;

import com.company.bean.CheckField;
import com.opencsv.CSVReader;
import com.opencsv.bean.CsvToBeanBuilder;
import com.opencsv.bean.HeaderColumnNameMappingStrategy;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.List;

/**
 * @author
 * @Date: 2021/1/23 19:55
 */
public class FileUtils {
    private static final String GBK = "GBK";
    private static final String UTF_8 = "UTF-8";
    private static final String UNICODE = "Unicode";
    private static final String UTF_16BE = "UTF-16BE";

    /**
     * 读取csv文件，并转成对象
     * 本次为全部读取，后续可做优化，一次读取部分
     *
     * @param filePath
     * @return
     * @throws Exception
     */
    public static List<CheckField> readFile(String filePath) throws Exception {
        CSVReader reader = new CSVReader(new InputStreamReader(new FileInputStream(filePath), codeString(filePath)));
        HeaderColumnNameMappingStrategy<CheckField> mapper = new HeaderColumnNameMappingStrategy<>();
        mapper.setType(CheckField.class);
        List<CheckField> cks = new CsvToBeanBuilder<CheckField>(reader)
                .withMappingStrategy(mapper)
                .build()
                .parse();
        return cks;
    }

    /**
     * 检查文件编码
     *
     * @param fileName
     * @return
     * @throws Exception
     */
    public static String codeString(String fileName) throws Exception {
        BufferedInputStream bin = new BufferedInputStream(new FileInputStream(fileName));
        int p = (bin.read() << 8) + bin.read();
        bin.close();
        String code;
        switch (p) {
            case 0xefbb:
                code = UTF_8;
                break;
            case 0xfffe:
                code = UNICODE;
                break;
            case 0xfeff:
                code = UTF_16BE;
                break;
            default:
                code = GBK;
        }

        return code;
    }
}
